package com.charonmc.listeners;

import com.charonmc.CharonCore;
import com.charonmc.commands.Nick;
import com.charonmc.events.PlayerAfterLoginListener;
import com.charonmc.utils.VanishUtils;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

/**
 * @author ChuYang
 */
public class PlayerListenerCore implements Listener {
    @EventHandler
    public void onPlayerJoinCore(PlayerJoinEvent event) {
        event.setJoinMessage("");
        //玩家进入服务器的基本设置
        Player player = event.getPlayer();
        player.playSound(player.getLocation(), Sound.ORB_PICKUP,2.0f, 1.5f);
        //Vanish命令的实现
        if (!player.hasPermission("Core.Vanish")) {
            //如果玩家没有隐身权限
            for (Player key : VanishUtils.getVanishPlayers()) {
                player.hidePlayer(key);
            }
        }

    }
    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        event.setQuitMessage("");
        //玩家退出服务器的优化交互
        Player player = event.getPlayer();
        Bukkit.getServer().broadcastMessage("§8[§c-§8] " + player.getDisplayName());
        player.playSound(player.getLocation(), Sound.ORB_PICKUP, 2.0f, 1.5f);
        //Vanish命令的补充
        //这里判断权限是为了防止本来就有权限的玩家重复执行for循环，节省资源
        if (!player.hasPermission("Core.Vanish")) {
            for (Player key : VanishUtils.getVanishPlayers()) {
                player.showPlayer(key);
            }
        }
        //清理玩家Nick
        event.getPlayer().setPlayerListName(event.getPlayer().getName());
        event.getPlayer().setDisplayName(event.getPlayer().getName());
    }

    @EventHandler
    public void sendJoinMessage(PlayerAfterLoginListener event){
        Bukkit.getServer().broadcastMessage("§8[§a+§8] " + event.getPlayer().getDisplayName());
        Bukkit.getScheduler().runTaskLater(CharonCore.instance, () -> {
            Nick.refreshNick(event.getPlayer());
        }, 5);
    }

}

